<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\Front\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CategoriesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories = Category::all()->groupBy('parent_id');
        $categories['root'] = $categories[0];
        unset($categories[0]);
        // dd($categories);

        return view('admin.categories.index', ['categories'=>$categories]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if (!isset($request->parent_id)) {
            $request->parent_id = 0;
        }
        Category::create([
                  'name'=>$request->name,
                  'slug'=>$request->slug,
                  'parent_id'=>$request->parent_id,
                  'is_floor'=>$request->is_floor,
                  'floor_color'=>'',
            ]);
        $this->clearHomeCache();
        Cache::forget('cates');
        return back();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        Category::where('id', $id)->update([
                'name'=>$request->name,
                  'slug'=>$request->slug,
                  'parent_id'=>$request->parent_id,
                  'is_floor'=>$request->is_floor,
                  'floor_color'=>$request->floor_color
            ]);
        $this->clearHomeCache();
        Cache::forget('cates');
        
        return back();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Category::find($id)->delete();
        $this->clearHomeCache();
        Cache::forget('cates');
        
        return back();
    }
}
